package com.code.monitor.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author ggh
 * @date 2023/5/8
 */
public class IOUtils {
    public static String readInputStream(InputStream inputStream, Charset charset) {
        String result = null;
        try {
            if (inputStream == null) {
                return "";
            }
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            StringBuffer stringBuffer = new StringBuffer();
            try {
                byte[] bus = new byte[8192];
                int n = -1;
                while ((n = bis.read(bus)) != -1) {
                    stringBuffer.append(new String(bus, 0, n, charset));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static byte[] readInputStreamToByte(InputStream inputStream) {
        String result = null;
        try {
            if (inputStream == null) {
                return null;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            StringBuffer stringBuffer = new StringBuffer();
            try {
                byte[] bus = new byte[8192];
                int n = -1;
                while ((n = bis.read(bus)) != -1) {
                    baos.write(bus, 0, n);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            baos.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
